<template>
<!-- 农合经办机构管理 -->
  <div class="cooperative-institution-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="机构名称">
              <el-input
                v-model="searchForm.institutionName"
                placeholder="请输入机构名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="机构编码">
              <el-input
                v-model="searchForm.institutionCode"
                placeholder="请输入机构编码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="所属行政编码">
              <el-input
                v-model="searchForm.regionCode"
                placeholder="请输入所属行政编码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增机构
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="institutionId" label="机构ID" width="100" align="center" />
        <el-table-column prop="institutionCode" label="机构编码" width="180" align="center" />
        <el-table-column prop="institutionName" label="机构名称" width="120" align="center" />
        <el-table-column prop="regionCode" label="所属行政编码" width="120" align="center" />
        <el-table-column prop="level" label="级别" width="80" align="center">
          <template #default="{row}">
            <el-tag :type="row.level === 1? 'primary' : 'info'" size="small">
              {{ row.level === 1? '县级' : '乡镇级' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="机构地址" width="180" align="center" />
        <el-table-column prop="contactPerson" label="联系人" width="120" align="center" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{row}">
            <el-tag :type="row.status === 1? 'success' : 'danger'" size="small">
              {{ row.status === 1? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{row}">
            {{ formatDate(row.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="{row}">
            {{ formatDate(row.updateTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              plain
              @click="toggleSingleStatus(row)"
            >
              {{ row.status === 1? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构名称" prop="institutionName">
              <el-input v-model="formData.institutionName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构编码" prop="institutionCode">
              <el-input v-model="formData.institutionCode" placeholder="请输入机构编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属行政编码" prop="regionCode">
              <el-input v-model="formData.regionCode" placeholder="请输入所属行政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="级别" prop="level">
              <el-select v-model="formData.level" placeholder="请选择级别" style="width:100%">
                <el-option label="县级" value="1" />
                <el-option label="乡镇级" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入机构地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width:100%">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="formData.createTime"
                type="datetime"
                placeholder="选择创建时间"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker
                v-model="formData.updateTime"
                type="datetime"
                placeholder="选择更新时间"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate } from '@/utils/date'

export default {
  name: 'CooperativeInstitutionAdmin',
  data() {
    return {
      // 搜索参数
      searchForm: {
        institutionName: '',
        institutionCode: '',
        regionCode: ''
      },

      // 表格数据
      tableData: [],
      loading: false,

      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新增农合经办机构',
      formData: {
        institutionId: null,
        institutionCode: '',
        institutionName: '',
        regionCode: '',
        level: 1,
        address: '',
        contactPerson: '',
        contactPhone: '',
        status: 1,
        createTime: new Date(),
        updateTime: new Date()
      },

      // 表单验证规则
      formRules: {
        institutionName: [
          { required: true, message: '请输入机构名称', trigger: 'blur' },
          { min: 2, max: 50, message: '机构名称长度2-50位', trigger: 'blur' }
        ],
        institutionCode: [
          { required: true, message: '请输入机构编码', trigger: 'blur' },
          { min: 1, max: 20, message: '机构编码长度1-20位', trigger: 'blur' }
        ],
        regionCode: [
          { required: true, message: '请输入所属行政编码', trigger: 'blur' },
          { min: 1, max: 20, message: '所属行政编码长度1-20位', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择级别', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入机构地址', trigger: 'blur' },
          { min: 2, max: 100, message: '机构地址长度2-100位', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人长度2-20位', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的联系电话', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        createTime: [
          { required: true, message: '请选择创建时间', trigger: 'change' }
        ],
        updateTime: [
          { required: true, message: '请选择更新时间', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDate,
    // 获取农合经办机构列表
    fetchData() {
      this.loading = true
      request.get('/cooperativeInstitution/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          institutionName: this.searchForm.institutionName,
          regionCode: this.searchForm.regionCode
        }
      })
      .then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      })
      .catch(err => {
        console.error('获取农合经办机构列表失败:', err)
        this.$message.error('加载农合经办机构列表失败')
      })
      .finally(() => {
        this.loading = false
      })
    },
    //搜索农合经办机构
    handleSearch() {
      this.pagination.currentPage = 1
      this.loading = true

      // 构建查询参数
      const queryParams = {
        current: this.pagination.currentPage,
        size: this.pagination.pageSize,
        institutionName: this.searchForm.institutionName,
        institutionCode: this.searchForm.institutionCode,
        regionCode: this.searchForm.regionCode
      }

      // 移除空值参数
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === undefined || queryParams[key] === '') {
          delete queryParams[key]
        }
      })

      request.post('/cooperativeInstitution/query', queryParams)
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records
            this.pagination.total = res.data.total
          } else {
            this.$message.error(res.message || '获取数据失败')
          }
        })
        .catch(err => {
          console.error('搜索失败:', err)
          this.$message.error('搜索失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    //重置搜索
    resetSearch() {
      this.searchForm = {
        institutionName: '',
        institutionCode: '',
        regionCode: ''
      }
      this.handleSearch()
    },
    //分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    //当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    //新增农合经办机构
    handleAdd() {
      this.dialogTitle = '新增农合经办机构'
      this.resetForm()
      this.dialogVisible = true
    },
    //编辑农合经办机构
    handleEdit(row) {
      this.dialogTitle = '编辑农合经办机构'
      this.formData = {
        ...row,
        // 确保日期字段是 Date 对象
        createTime: row.createTime ? new Date(row.createTime) : new Date(),
        updateTime: row.updateTime ? new Date(row.updateTime) : new Date()
      }
      this.dialogVisible = true
    },
    // 删除单个农合经办机构
    handleDelete(row) {
      this.$confirm(`确认删除机构 "${row.institutionName}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post(`/cooperativeInstitution/delete/${row.institutionId}`)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
          .catch(err => {
            console.error('删除机构失败:', err)
            this.$message.error('删除失败')
          })
      }).catch(() => {})
    },

    // 切换单个机构状态
    toggleSingleStatus(row) {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      this.$confirm(`确认${statusText}机构 "${row.institutionName}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post(`/cooperativeInstitution/update`, {
          institutionId: row.institutionId,
          status: newStatus
        })
        .then(res => {
          if (res.code === 200) {
            this.$message.success(`${statusText}成功`)
            this.fetchData()
          } else {
            this.$message.error(res.message || `${statusText}失败`)
          }
        })
        .catch(err => {
          console.error(`${statusText}机构失败:`, err)
          this.$message.error(`${statusText}失败`)
        })
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        // 创建一个临时对象，处理日期格式
        const formDataToSubmit = { ...this.formData }
        
        // 将日期对象格式化为 YYYY-MM-DD HH:mm:ss 字符串
        if (formDataToSubmit.createTime instanceof Date) {
          formDataToSubmit.createTime = formatDate(formDataToSubmit.createTime, 'YYYY-MM-DD HH:mm:ss')
        }
        
        if (formDataToSubmit.updateTime instanceof Date) {
          formDataToSubmit.updateTime = formatDate(formDataToSubmit.updateTime, 'YYYY-MM-DD HH:mm:ss')
        }

        const isEdit = !!this.formData.institutionId
        const apiUrl = isEdit ? '/cooperativeInstitution/update' : '/cooperativeInstitution/create'
        const method = 'post'

        request[method](apiUrl, formDataToSubmit)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || `${this.dialogTitle}失败`)
            }
          })
          .catch(err => {
            console.error(`${this.dialogTitle}失败:`, err)
            this.$message.error(`${this.dialogTitle}失败`)
          })
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      
      // 重置表单数据
      this.formData = {
        institutionId: null,
        institutionCode: '',
        institutionName: '',
        regionCode: '',
        level: 1,
        address: '',
        contactPerson: '',
        contactPhone: '',
        status: 1,
        createTime: new Date(),
        updateTime: new Date()
      }
    }
  }
}
</script>

<style scoped>
.cooperative-institution-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display: flex;
  margin-bottom: 20px;
}

.operation-buttons > * {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

/* 新增表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
}

/* 保持表格宽度足够显示所有列 */
.el-table {
  min-width: 1200px; /* 根据实际列宽调整这个值 */
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
  
  .operation-buttons {
    flex-wrap: wrap;
  }
  
  .operation-buttons > * {
    margin-bottom: 10px;
  }
}
</style>